package com.example.scanidcard;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.example.scanidcard.IdentifyResult;

public class MainActivity extends AppCompatActivity{
    private Button btn_scan;
    public static final int TAKE_PHOTO = 1;// 系统相机
    private ImageView picture;
    private Uri Imageuri;
    private File outputImage;
    private IdentifyResult result;
    private TextView textView,textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_scan = (Button) findViewById(R.id.btn1);
        picture = (ImageView) findViewById(R.id.picture);
        textView = (TextView) findViewById(R.id.tv1);
        textView2 = (TextView)findViewById(R.id.tv2);
        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建File对象，用于存储拍照后的图片
                outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                try{
                    if (!outputImage.exists()){//当前图片不存在
                        outputImage.createNewFile();//重新创建新文件
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    Imageuri = FileProvider.getUriForFile(MainActivity.this,
                            "com.example.scanidcard.fileprovider", outputImage);
                } else {
                    Imageuri = Uri.fromFile(outputImage);
                }
                // 启用相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//捕获图片
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Imageuri);
                launcher.launch(intent);
            }
        });
    }
    public ActivityResultLauncher<Intent> launcher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>(){
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK){
                        //使用身份证识别接口获取
                        IdCardDetails(getHandler_IdCard);
                        try {
                           //显示已拍照图片
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Imageuri));
                        picture.setImageBitmap(bitmap);
                        Toast.makeText(MainActivity.this, outputImage.toString(), Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    }
                }
            });

     Handler getHandler_IdCard = new Handler(){
         @Override
         public void handleMessage(@NonNull Message msg) {
             super.handleMessage(msg);
             String str = msg.getData().getString("request");
//             toast("str:"+str);
             JSONObject jsonObj = null;
             try {
                 jsonObj = new JSONObject(str);
             } catch (JSONException e) {
                 e.printStackTrace();
             }
             try {
                 //获取的数据是json格式，以"Response"作为获取数据返回标签
                 result = new Gson().fromJson(jsonObj.get("Response").toString(),IdentifyResult.class);
                 is_null(result);
                 textView.setText(getString(result));
             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     };



    /**
     * 身份证扫描结果
     */
    public void IdCardDetails(final Handler handler){
        String str = null;
        if (outputImage.exists()) {
            str = outputImage.toString();
            toast("找到图片:"+str);
        } else {
            toast("找不到图片");
            return;
        }
        //利用腾讯云V3签名算法封装图片，将封装后的数据上传至腾讯云服务器，再获得服务器返回数据
        TecentHttpUtil.getIdCardDetails(str,
                new TecentHttpUtil.SimpleCallBack() {
                    @Override
                    public void Succ(String res) {
                        //可以查看获取到的数据，这里存在一个permission denied要添加一个权限
//                        toast("res:"+res);
                        Message message = new Message();
                        Bundle bd = new Bundle();
                        bd.putString("request", res);
                        message.setData(bd);
                        handler.sendMessage(message);
                        toast("识别成功");
                    }
                    @Override
                    public void error() {
                        toast("识别错误");
                    }
                });
    }

    public void is_null(IdentifyResult result) {
        if ( "FailedOperation.ImageNoIdCard".equals(result.getError().getCode())) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("请拍摄完整身份证")
                    .setTitle("提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            try {
                                dialog.dismiss();
                            } catch (Exception e) {
                                // 记录日志或者进行合适的提示等操作
                                Log.e("DialogError", "Error dismissing dialog: " + e.getMessage());
                            }
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

    public String getString(IdentifyResult result) {
        String str = result.getName() + "\n"
                    + result.getSex() + "\n"
                    + result.getNation() + "\n"
                    + result.getBirth() + "\n"
                    + result.getAddress() + "\n"
                    + result.getIdNum();
        return str;
    }

    public void toast(String str) {
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }

}